import { ref } from 'vue'

export function useDrawing(canvas) {
    const isDrawingLine = ref(false)
    let line = null, startPoint = null

    const startDrawingLine = (opt) => {
        if (!isDrawingLine.value) return
        const pointer = canvas.getPointer(opt.e)
        startPoint = pointer

        line = new fabric.Line([pointer.x, pointer.y, pointer.x, pointer.y], {
            stroke: '#000000',
            strokeWidth: 1,
            selectable: true,
            hasBorders: true,
            hasControls: true
        })
        canvas.add(line)
        canvas.requestRenderAll()
    }

    const drawLine = (opt) => {
        if (!isDrawingLine.value || !line) return
        const pointer = canvas.getPointer(opt.e)
        line.set({ x2: pointer.x, y2: pointer.y })
        canvas.requestRenderAll()
    }
    const finishDrawingLine = () => {
        if (!isDrawingLine.value || !line) return;

        const endPoint = { x: line.get('x2'), y: line.get('y2') };
        const distance = Math.sqrt(
            Math.pow(endPoint.x - startPoint.x, 2) +
            Math.pow(endPoint.y - startPoint.y, 2)
        );

        if (distance < 5) {
            canvas.remove(line);
        } else {
            line.selectable = true;
            line.perPixelTargetFind = true; // 启用 perPixelTargetFind
            canvas.setActiveObject(line);
            line.bringToFront(); // 将线条带到最前
        }
        line = null;
        startPoint = null;
        isDrawingLine.value = false;

        canvas.selection = true;
        canvas.forEachObject(obj => obj.selectable = true);
        // 恢复默认鼠标样式
        canvas.defaultCursor = 'default';
        canvas.hoverCursor = 'move';
        canvas.requestRenderAll();
    }

    const toggleLineDrawing = () => {
        isDrawingLine.value = !isDrawingLine.value

        if (isDrawingLine.value) {
            canvas.selection = false
            canvas.forEachObject(obj => obj.selectable = false)
            // 设置十字鼠标样式
            canvas.defaultCursor = 'crosshair'
            canvas.hoverCursor = 'crosshair'
        } else {
            canvas.selection = true
            canvas.forEachObject(obj => obj.selectable = true)
            // 恢复默认鼠标样式
            canvas.defaultCursor = 'default'
            canvas.hoverCursor = 'move'
        }
        canvas.requestRenderAll()
    }

    return {
        isDrawingLine,
        startDrawingLine,
        drawLine,
        finishDrawingLine,
        toggleLineDrawing
    }
}